package com.baeldung.keycloak;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.keycloak.client.registration.Auth;
import org.keycloak.client.registration.ClientRegistration;
import org.keycloak.client.registration.ClientRegistrationException;
import org.keycloak.representations.idm.ClientRepresentation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Client Registration
 * https://www.keycloak.org/docs/latest/securing_apps/index.html#example-using-java-client-registration-api
 */
@RestController
@Slf4j
public class ClientRegisterController {
    private final static String authServerUrl = "http://localhost:8083/auth";
    private final static String realm = "SpringBootKeycloak";
    private final static String clientId = "we-openid-1";
    // private final static String clientId = "login-app";
    // private final static String clientId = "account";
    private final static Map<String, Object> clientCredentials = Map.of("secret", "2593357d-c297-4331-be37-52740f900601");
    private final static HttpClient httpClient = HttpClients.createDefault();

    @GetMapping("/client")
    public void clientRegister() throws ClientRegistrationException {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0YjhiZjlhNi03ODlmLTQ0NjItYTVlZS1hYzhiZWY5Nzk1MWMifQ.eyJqdGkiOiJlZmRmMGIyNy04ZWQyLTQwMmUtYThlYS0yYzQyOWRlYjUxNTEiLCJleHAiOjE1ODg1NjEwMTEsIm5iZiI6MCwiaWF0IjoxNTg3Njk3MDExLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODMvYXV0aC9yZWFsbXMvU3ByaW5nQm9vdEtleWNsb2FrIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgzL2F1dGgvcmVhbG1zL1NwcmluZ0Jvb3RLZXljbG9hayIsInR5cCI6IkluaXRpYWxBY2Nlc3NUb2tlbiJ9.r4j_4ZX7qzejSmY9HljrPbMg9R9pNkBARynr9rsCnR4";

        ClientRepresentation client = new ClientRepresentation();
        client.setClientId(clientId);

        ClientRegistration reg = ClientRegistration.create()
                .url(authServerUrl, realm)
                .build();

        reg.auth(Auth.token(token));

        client = reg.create(client);

        String registrationAccessToken = client.getRegistrationAccessToken();
        System.out.println(registrationAccessToken);
    }
}
